package com.qf.commons.sentinel.config;

import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;

import java.util.List;

/**
 * 应用启动时初始化
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
@Slf4j
public class ApplicationRunning implements CommandLineRunner {

    @Autowired
    private SentinelNacosConfig sentinelNacosConfig;

    @Override
    public void run(String... args) throws Exception {
        log.info("[sentinel config load] - 微服务加载sentinel的相关配置！{}", sentinelNacosConfig);

        //从Nacos上加载限流规则
        ReadableDataSource<String, List<FlowRule>> datasource = new NacosDataSource<>(
                sentinelNacosConfig.getHost(),
                sentinelNacosConfig.getGroup(),
                sentinelNacosConfig.getApplication() + sentinelNacosConfig.getFlowPrefix(),
                source -> JSON.parseArray(source, FlowRule.class)
        );
        //从配置中加载流控规则
        FlowRuleManager.register2Property(datasource.getProperty());

        //从Nacos上加载熔断降级规则
        ReadableDataSource<String, List<DegradeRule>> datasource2 = new NacosDataSource<>(
                sentinelNacosConfig.getHost(),
                sentinelNacosConfig.getGroup(),
                sentinelNacosConfig.getApplication() + sentinelNacosConfig.getDegradePrefix(),
                source -> JSON.parseArray(source, DegradeRule.class)
        );
        //从配置中加载降级规则
        DegradeRuleManager.register2Property(datasource2.getProperty());
    }
}
